import React, { useState } from "react";
import { Form, Input, Button, message } from "antd";
import { modifyPassword } from "../../api/ckgl";
import { useNavigate } from "react-router-dom";

const PasswordResetPage = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate(); // Access the navigate function using useNavigate

  const handlePasswordReset = async (values: any) => {
    setLoading(true);
    try {
      // TODO: user_id 是当前用户自己的

      const { old_password, new_password } = values;
      // Call modifyPassword API
      const modifyPasswordRes = await modifyPassword({
        user_id: localStorage?.user_id,
        old_password,
        new_password,
      });

      //   if (modifyPasswordRes?.code !== 0) {
      //     message.error(modifyPasswordRes.msg);
      //     return;
      //   }

      message.success("密码更新成功");
      navigate("/login");
      localStorage.removeItem("react-jwt-token");
      localStorage.removeItem("token");
      localStorage.removeItem("role_code");
      localStorage.removeItem("user_id");
      // Reset the form
      form.resetFields();
    } catch (error) {
      console.error("Password reset failed:", error);
      message.error("密码更新失败");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: "400px", margin: "auto", marginTop: "50px" }}>
      <Form form={form} onFinish={handlePasswordReset}>
        <Form.Item
          label="旧密码"
          name="old_password"
          rules={[
            {
              required: true,
              message: "请输入旧密码",
            },
          ]}
        >
          <Input.Password placeholder="旧密码" />
        </Form.Item>
        <Form.Item
          label="新密码"
          name="new_password"
          rules={[
            {
              required: true,
              message: "请输入新密码",
            },
          ]}
        >
          <Input.Password placeholder="新密码" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading}>
            确定
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default PasswordResetPage;
